from machine import UART
from machine import Pin
from machine import Pin,ADC
from machine import Pin, PWM
import time

uart=UART(2,115200)
uart.write('READY')

CS = Pin(2, Pin.OUT)
SCK = Pin(15, Pin.OUT)
SO = Pin(4, Pin.IN)
tdata=0

DIP = Pin(18, Pin.OUT)
STEP = PWM(Pin(19))

PU = Pin(12, Pin.IN)
PD = Pin(27, Pin.IN)

while True:  
    if uart.any():
        text = uart.read(20)
        if text.decode('utf-8') == "\x01":#温度检测
            for q in range(10):
                i=0 
                tdat=0
                CS.off()
                for i in range(16):
                    SCK.on()
                    tdat = tdat<<1
                    if SO.value():
                        tdat = tdat|0x01
                    SCK.off()
                tdat=((tdat&0x7FF8)>>3)/4
                tdata=tdata+tdat/10
                CS.on()
                time.sleep_ms(200)
            tdata_str = str(tdata)
            uart.write(tdata_str)
        if text.decode('utf-8') == "\x02":#湿度检测
            adc = ADC(Pin(13))
            adc.atten(ADC.ATTN_11DB)
            sdat=str(abs(adc.read()-1930)/19.3)
            uart.write(sdat)
        if text.decode('utf-8') == "\x03":#电机向上
            DIP.off()
            STEP.freq(600)
            STEP.duty(128)
        if text.decode('utf-8') == "\x04":#电机向下
            DIP.on()
            STEP.freq(600)
            STEP.duty(128)
        if text.decode('utf-8') == "\x05":#自动
            if PD.value() != 0:
                while PD.value() != 0:
                    DIP.on()
                    STEP.freq(600)
                    STEP.duty(128)
                STEP.duty(0)
                uart.write("DOWN")
                for q in range(10):
                    i=0 
                    tdat=0
                    CS.off()
                    for i in range(16):
                        SCK.on()
                        tdat = tdat<<1
                        if SO.value():
                            tdat = tdat|0x01
                        SCK.off()
                    tdat=((tdat&0x7FF8)>>3)/4
                    tdata=tdata+tdat/10
                    CS.on()
                    time.sleep_ms(200)
                tdata_str = str(tdata)
                uart.write(tdata_str)
                adc = ADC(Pin(13))
                adc.atten(ADC.ATTN_11DB)
                sdat=str(abs(adc.read()-1930)/19.3)
                uart.write(sdat)
                while PU.value() != 0:
                    DIP.off()
                    STEP.freq(600)
                    STEP.duty(128)
                STEP.duty(0)
                uart.write("STOP")           
        text=0;
        